In this notebook, you will compile the visualizations from the previous analysis into functions that can be used for a Panel dashboard.
# imports
import panel as pn
pn.extension('plotly')
import plotly.express as px
import pandas as pd
import hvplot.pandas
import matplotlib.pyplot as plt
import os
from pathlib import Path
from dotenv import load_dotenv
from panel.interact import interact
from panel import widgets
Bad key "text.kerning_factor" on line 4 in C:\Users\yyamamoto\Anaconda3\envs\pyvizenv\lib\site-packages\matplotlib\mpl-data\stylelib\_classic_test_patch.mplstyle. You probably need to get an updated matplotlibrc file from http://github.com/matplotlib/matplotlib/blob/master/matplotlibrc.template or from the matplotlib source distribution
# Read the Mapbox API key
load_dotenv()
map_box_api = os.getenv("mapbox")
px.set_mapbox_access_token(map_box_api)
# Import the necessary CSVs to Pandas DataFrames
file_path = Path("Data/sfo_neighborhoods_census_data.csv")
sfo_data = pd.read_csv(file_path, index_col="year")
sfo_data.head()
| neighborhood | sale_price_sqr_foot | housing_units | gross_rent | |
|---|---|---|---|---|
| year | ||||
| 2010 | Alamo Square | 291.182945 | 372560 | 1239 |
| 2010 | Anza Vista | 267.932583 | 372560 | 1239 |
| 2010 | Bayview | 170.098665 | 372560 | 1239 |
| 2010 | Buena Vista Park | 347.394919 | 372560 | 1239 |
| 2010 | Central Richmond | 319.027623 | 372560 | 1239 |
In this section, you will copy the code for each plot type from your analysis notebook and place it into separate functions that Panel can use to create panes for the dashboard.
These functions will convert the plot object to a Panel pane.
Be sure to include any DataFrame transformation/manipulation code required along with the plotting code.
Return a Panel pane object from each function that can be used to build the dashboard.
Note: Remove any .show() lines from the code. We want to return the plots instead of showing them. The Panel dashboard will then display the plots.
# Pane 1 Housing Units: Define Panel Visualization Functions
def housing_units_per_year():
housing_units=sfo_data.loc[:, 'housing_units']
units_per_year = housing_units.groupby(['year']).mean()
default_plot=units_per_year.plot(kind='bar', title='Housing Units in San Francisco from 2010 to 2016')
return default_plot
interact(housing_units_per_year)
# Pane 2 Gross Rent: Define Panel Visualization Functions
def average_gross_rent():
ave_price_rent=sfo_data.drop(columns=['neighborhood', 'housing_units'])
ave_price_rent_year = ave_price_rent.groupby(['year']).mean()
average_gross_rent=ave_price_rent_year.plot(y="gross_rent", color="red", legend=False, title='Average Gross Rent by Year')
average_gross_rent.set_xlabel("Year")
average_gross_rent.set_ylabel("Average Gross Rent")
return average_gross_rent
interact(average_gross_rent)
# Pane 3 Sale Price: Define Panel Visualization Functions
def average_sales_price():
ave_price_rent=sfo_data.drop(columns=['neighborhood', 'housing_units'])
ave_price_rent_year = ave_price_rent.groupby(['year']).mean()
average_price_sqr=ave_price_rent_year.plot(y="sale_price_sqr_foot", color="purple", legend=False, title='Average Price per SqFt by Year')
average_price_sqr.set_xlabel("Year")
average_price_sqr.set_ylabel("Price per SqFt")
return average_price_sqr
interact(average_sales_price)
# Pane 4 neighborhood: Define Panel Visualization Functions
def average_price_by_neighborhood():
ave_price_sqr_by_neighborhood=sfo_data.groupby(['year','neighborhood'] ).mean()
average_price_by_neighborhood = ave_price_sqr_by_neighborhood.hvplot.line(x='year', y='sale_price_sqr_foot',
groupby='neighborhood', xlabel='Year', ylabel='Ave. Sale Price per SqFt')
return average_price_by_neighborhood
interact(average_price_by_neighborhood)
# Pane 5 most expensive: Define Panel Visualization Functions
def top_most_expensive_neighborhoods():
expensive=sfo_data.groupby('neighborhood').mean()
sorted_expensive=expensive.sort_values(by=['sale_price_sqr_foot'], ascending=False)
top_ten=sorted_expensive.iloc[0:10]
return top_ten.hvplot.bar(x='neighborhood', y='sale_price_sqr_foot',
title='Top 10 Expensive Neighborhoods in SFO', xlabel='Neighborfood', ylabel='Ave. Sale Price per SqFt'
,rot=90, height=500)
interact(top_most_expensive_neighborhoods)
# Pane 6: Define Panel Visualization Functions
def most_expensive_neighborhoods_rent_sales():
ave_price_sqr_by_neighborhood=sfo_data.groupby(['year','neighborhood'] ).mean()
return ave_price_sqr_by_neighborhood.hvplot.bar(x='year', y=['gross_rent', 'sale_price_sqr_foot'],
groupby='neighborhood', height=500, width=700, rot=90)
interact(most_expensive_neighborhoods_rent_sales)
# Pane 7: Define Panel Visualization Functions
def parallel_categories():
expensive=sfo_data.groupby('neighborhood').mean()
sorted_expensive=expensive.sort_values(by=['sale_price_sqr_foot'], ascending=False)
top_ten=sorted_expensive.iloc[0:10]
top_ten_index=top_ten.reset_index()
plot=px.parallel_categories(top_ten_index,
dimensions=['neighborhood','sale_price_sqr_foot','housing_units', 'gross_rent'],
color='sale_price_sqr_foot',
color_continuous_scale=px.colors.sequential.Inferno,
width=1200
)
return plot
interact(parallel_categories)
#Pane 8: Define Panel Visualization Functions
def parallel_coordinates():
expensive=sfo_data.groupby('neighborhood').mean()
sorted_expensive=expensive.sort_values(by=['sale_price_sqr_foot'], ascending=False)
top_ten=sorted_expensive.iloc[0:10]
top_ten_index=top_ten.reset_index()
pd.options.display.float_format = '{:,.2f}'.format
top_ten_coordinates=top_ten_index.drop(columns=['neighborhood'])
plot_coord=px.parallel_coordinates(top_ten_coordinates, color='sale_price_sqr_foot',
width=1200)
return plot_coord
interact(parallel_coordinates)
# Load neighborhoods coordinates data
# Read the census data into a Pandas DataFrame
coordinates_file_path = Path("Data/neighborhoods_coordinates.csv")
coordiates_data = pd.read_csv(coordinates_file_path)
index_coordiates_data=coordiates_data.set_index('Neighborhood')
average=sfo_data.groupby('neighborhood').mean()
reset_average= average.reset_index()
renamed_average=reset_average.rename(columns={"neighborhood":"Neighborhood"})
index_renamed_average=renamed_average.set_index('Neighborhood')
combined_coordin_average=pd.concat([index_coordiates_data, index_renamed_average], axis="columns", join='inner')
#Pane 9: Define Panel Visualization Functions
def neighborhood_map():
map_sales_price = px.scatter_mapbox(
combined_coordin_average,
lat="Lat",
lon="Lon",
color="sale_price_sqr_foot",
size="housing_units",
zoom=10,
color_continuous_scale=px.colors.sequential.Bluered)
return map_sales_price
#Pane 10: Sunburst
def sunburst():
ave_price_sqr_by_neighborhood=sfo_data.groupby(['year','neighborhood'] ).mean()
ave_price_sqr_by_neighborhood
sorted_df_sunburst=ave_price_sqr_by_neighborhood.sort_values(by=['year', 'sale_price_sqr_foot'], ascending=False).groupby('year').head(10)
sorted_df_sunburst.reset_index(inplace=True)
sorted_df_sunburst
plot =px.sunburst(sorted_df_sunburst,
path=['year','neighborhood'],
values='sale_price_sqr_foot',
color='gross_rent',
color_continuous_scale ='mrybm')
return plot
# Welcome Screen
row_map=pn.Row("## Real Estate Analysis of San Francisco from 2010 to 2016", neighborhood_map())
row_map
# Welcome Screen
column_map=pn.Column("## Real Estate Analysis of San Francisco from 2010 to 2016", neighborhood_map())
column_map
In this section, you will combine all of the plots into a single dashboard view using Panel. Be creative with your dashboard design!
# Create a Title for the Dashboard
# Create a tab layout for the dashboard
welcome_column = pn.Column("## Real Estate Analysis of San Francisco from 2010 to 2016", neighborhood_map())
welcome_column
#Yearly analysis
row=pn.Row("## Real Estate Analysis of San Francisco from 2010 to 2016", housing_units_per_year(), average_gross_rent(), average_sales_price())
row
#Neighborhood column
by_neighborhood=pn.Column("## Real Estate Analysis of San Francisco from 2010 to 2016", average_price_by_neighborhood(),top_most_expensive_neighborhoods(), most_expensive_neighborhoods_rent_sales())
by_neighborhood
#parallel
parallels=pn.Column("## Real Estate Analysis of San Francisco from 2010 to 2016", parallel_categories(), parallel_coordinates())
parallels
#sunburst
sunburst_plot=pn.Row("## Real Estate Analysis of San Francisco from 2010 to 2016", sunburst())
sunburst_plot
# Create the dashboardy
tabs =pn.Tabs(
("Neighborhood", by_neighborhood),
("Yearly", row),
("Parallel", parallels),
("Sunburst", sunburst_plot)
)
tabs
# Serve the# dashboard
tabs.servable()
Note: Some of the Plotly express plots may not render in the notebook through the panel functions.
However, you can test each plot by uncommenting the following code
housing_units_per_year()
<matplotlib.axes._subplots.AxesSubplot at 0x1b2c4471f88>
average_gross_rent()
<matplotlib.axes._subplots.AxesSubplot at 0x1b2c4492fc8>
average_sales_price()
<matplotlib.axes._subplots.AxesSubplot at 0x1b2c44facc8>
average_price_by_neighborhood()
top_most_expensive_neighborhoods()
most_expensive_neighborhoods_rent_sales()
neighborhood_map().show()
parallel_categories()
parallel_coordinates()
sunburst()